package com.elves.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class UserRoleConfiguration {
    @Bean
    public UserDetailsService users() {
        UserDetails admin = User.withDefaultPasswordEncoder()
                .username("admin")
                .password("password")
                .roles("ADMIN")
                .build();
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();
        UserDetails vip = User.withDefaultPasswordEncoder()
                .username("vip")
                .password("password")
                .roles("VIP")
//                .authorities("vip")
                .build();
        return new InMemoryUserDetailsManager(admin, user, vip);
    }

//    @Bean
//    public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() { //(3)
//        return (context) -> {
//            if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { //(4)
//                context.getClaims().claims((claims) -> { //(5)
//                    Authentication authentication = context.getPrincipal();
//                    log.info("authentication:::{}", authentication);
//                    Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities())
//                            .stream()
//                            .map(c -> c.replaceFirst("^ROLE_", ""))
//                            .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet)); //(6)
//                    log.info("roles::{}", roles);
//                    claims.put("roles", roles); //(7)
//                });
//            }
//        };
//    }

}
